Lesson Log on Oct.12th
Dictionary
Today we discussed about the dictionary, a new data type.
First let's review the data type we had learned already:float, int, string, tuple, list and boolean.
string and tuple are immutable, list is mutable.
and dictionary, is a very flexible data type. it's index can be any type of data, like string.
The basic form of the dictionary is { index:value}.
we can consider it as a more flexible list, so we can use the method we used to get value from list in the dictionary type.
we can create a dictionary first:
alias point directly to the RAM address we save dictionary "opposites". so we can't change it directly, it will change the original value. so if we want change it, we need to copy it and then modify it.
with dictionary, we can make the program we already have work even better.
Like the program for Fibonacci's sequence. the dictionary can help us run it faster:
def fib(n):
if n<=1:
return n
t=fib(n-1)+fib(n-2)return t
print(fib(30))
alreadyknown={0:0,1:1}def fib(n):
if n notin alreadyknown:
new=fib(n-1)+fib(n-2)
alreadyknown[n]=newreturn alreadyknown[n]print(fib(997))
Dictionary
Today we discussed about the dictionary, a new data type.
First let's review the data type we had learned already:float, int, string, tuple, list and boolean.
string and tuple are immutable, list is mutable.
and dictionary, is a very flexible data type. it's index can be any type of data, like string.
The basic form of the dictionary is { index:value}.
we can consider it as a more flexible list, so we can use the method we used to get value from list in the dictionary type.
we can create a dictionary first:
now we create a dictionary to show the inventory.
we can delete the elements in the dictionary:
we can modify the value in the dictionary:
and there is some useful functions in the dictionary class.
for example:
we can show all the index in the dictionary:
we can put index and values in a tuple and range them in a list:
we can show the value for all the index too:
Dictionary is too flexible,we can change it anytime so we need to ensure we didn't change the original dictionary.
alias point directly to the RAM address we save dictionary "opposites". so we can't change it directly, it will change the original value. so if we want change it, we need to copy it and then modify it.
with dictionary, we can make the program we already have work even better.
Like the program for Fibonacci's sequence. the dictionary can help us run it faster:
That's some basic use of dictionary.